const validate = require('../../utils/validate')
const common = require('../../utils/common')
const { queryAftersalePage } = require('../../services/order')
const defaultPage = {
  curPage: 1,
  pageSize: 10,
}
Page({
  data: {
    total: 10,
    query: {
      ...defaultPage,
      searchNo: '',
      status: '',
    },
    orderList: [],
    loaded: false,
    tabList: [
      { name: '全部', value: '' },
      { name: '待退回', value: '11' },
      { name: '待返仓', value: '12' },
      { name: '售后失败', value: '14' },
      { name: '售后完成', value: '15' },
    ],
  },
  onLoad: function ({ searchNo }) {
    this.queryChange({ searchNo })
  },
  tabChange: function (e) {
    const { index } = e.currentTarget.dataset;
    const item = this.data.tabList[index];
    this.queryChange({ ...defaultPage, status: item.value })
  },
  queryChange: function (payload) {
    this.setData({
      query: { ...this.data.query, ...payload },
    }, this.getOrderList)
  },
  getOrderList: function (options) {
    if (this.data.query.curPage > 1 && this.data.orderList.length >= this.data.total) return
    const params = { ...this.data.query, ...options }
    queryAftersalePage(params).then(res => {
      const { total } = res.page
      this.setData({ total })
      if (params.curPage == 1) {
        this.setData({
          orderList: res.data
        })
      } else {
        this.setData({
          orderList: [...this.data.orderList, ...res.data]
        })
      }
      this.setData({
        loaded: true
      })
    }).catch(err => {
      common.log(err)
    })
  },
  scrollBottom: function () {
    const curPage = ++this.data.query.curPage
    this.queryChange({ curPage })
  },
  openSearchOrder: function (e) {
    wx.navigateTo({ url: '/pages/search-order/index?type=2' })
  },
  cancelSearch: function () {
    this.queryChange({ ...defaultPage, searchNo: "" })
  },
  goDetail: function (e) {
    const { index } = e.currentTarget.dataset;
    const item = this.data.orderList[index];
    wx.navigateTo({ url: `/pages/sell-order-info/index?id=${item.id}` })
  },
  makePhoneCall: function (e) {
    const { phone } = e.currentTarget.dataset;
    wx.makePhoneCall({
      phoneNumber: phone
    })
  }
})